package com.findme.fecedetection.ui.fragment

import android.app.Activity
import android.view.View
import android.widget.TextView
import com.findme.fecedetection.R
import com.findme.fecedetection.base.ImmersionTitleActivity
import com.findme.fecedetection.net.HttpManager
import com.findme.fecedetection.utlis.extend.checkCaptcha
import com.findme.fecedetection.utlis.extend.checkPassword
import com.findme.fecedetection.utlis.extend.checkPhoneNumber
import com.tanguy.user.utlis.extend.*
import org.jetbrains.anko.find

/**
 * Created by dab on 2017/11/20 0020 22:29
 * register=1 注册 2 登录
 */
class UserLoginActivity : ImmersionTitleActivity() {
    private var register = false
    override fun setContentViewRes(): Int = R.layout.activity_user_login
    override fun initEvent() {
        super.initEvent()
        register = intent.getBooleanExtra("register", false)
        refreshUI()
        click(R.id.iv_back) { finish() }
        click(R.id.tv_next) { next() }
        click(R.id.tv_get_captcha) { getCaptcha() }
        click(R.id.tv_register) { register() }
    }

    private fun getCaptcha() {
        val phone = getEditTextString(R.id.et_phone)
        if (!checkPhoneNumber(phone)) return
        HttpManager.getCode(phone)
                .requestSucceed(this) {
                    // 获取验证码
                    compositeDisposable.add(captchaCountDownTimer { finish, msg ->
                        val find = find<TextView>(R.id.tv_get_captcha)
                        find.isClickable = finish
                        find.text = msg
                    })
                }
    }

    private fun register() {
        register = !register
        refreshUI()
    }

    private fun refreshUI() {
        if (!register) {
            find<View>(R.id.view_captcha).visibility = View.GONE
            setText(R.id.tv_register, "注册")
            setText(R.id.tv_next, "登录")
        } else {
            find<View>(R.id.view_captcha).visibility = View.VISIBLE
            setText(R.id.tv_register, "登录")
            setText(R.id.tv_next, "注册")
        }
    }

    private fun next() {
        val phone = getEditTextString(R.id.et_phone)
        if (!checkPhoneNumber(phone)) return
        val password = getEditTextString(R.id.et_password)
        if (!checkPassword(password)) return
        if (register) {
            val captcha = getEditTextString(R.id.et_captcha)
            if (!checkCaptcha(captcha)) return
            HttpManager.regist(phone, password, captcha)
                    .requestSucceed(this) {
                        loge(it)
                        finish()
                    }
        } else {
            HttpManager.login(phone, password)
                    .requestSucceed(this) {
                        loge(it)
                        setResult(Activity.RESULT_OK)
                        finish()
                    }
        }

    }
}